/*
 * Copyright 2011 www.pretty-tools.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "stdafx.h"
#include "DOMSerializer.h"


// CDOMSerializer

CDOMSerializer::CDOMSerializer()
{
    ATLTRACE( _T("CDOMSerializer::CDOMSerializer()\n") );
}

CDOMSerializer::~CDOMSerializer()
{
    ATLTRACE( _T("CDOMSerializer::~CDOMSerializer()\n") );
}

STDMETHODIMP CDOMSerializer::serializeToString(VARIANT root, BSTR* pRet)
{
    if (!pRet)
        return E_POINTER;

    if (root.vt != VT_DISPATCH)
        return E_INVALIDARG;

    CComQIPtr<IXMLDOMNode> pRootNode = root.pdispVal;
    if (!pRootNode)
        return E_INVALIDARG;

    return pRootNode->get_xml(pRet);
}

STDMETHODIMP CDOMSerializer::serializeToStream(VARIANT root, VARIANT stream, VARIANT charset)
{
    if (root.vt != VT_DISPATCH)
        return E_INVALIDARG;
    if (stream.vt != VT_DISPATCH)
        return E_INVALIDARG;

    CComQIPtr<IXMLDOMNode> pRootNode = root.pdispVal;
    if (!pRootNode)
        return E_INVALIDARG;

    CComQIPtr<IXMLDOMDocument> pDocument = root.pdispVal;
    if (!pDocument)
        RETURN_FAILED(pRootNode->get_ownerDocument(&pDocument))
    if (!pDocument)
        return E_FAIL;

    CComQIPtr<IOutputStream> pOutputStream(stream.pdispVal);
    if (pOutputStream)
    {
        CComBSTR bsXML;
        RETURN_FAILED(pDocument->get_xml(&bsXML))

        if (wcsstr(bsXML, L"<?xml"))
        {
            CStringW xml = wcsstr(bsXML, L"?>") + 2;
            bsXML = CComBSTR((CStringW)"<?xml version='1.0' encoding='UTF-8'?>" + xml);
        }
        else
        {
            bsXML = CComBSTR((CStringW)"<?xml version='1.0' encoding='UTF-8'?>\n" + bsXML);
        }

        LONG nCount = 0;
        RETURN_FAILED(pOutputStream->write(bsXML, bsXML.Length(), &nCount))
        RETURN_HRESULT(((unsigned int)nCount) >= bsXML.Length());
    }

    return E_NOTIMPL;
}
